<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1"> -->
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Intel Experience Kit | Transportation Use Case</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom -->
    <link href="css/main.css" rel="stylesheet">
    <link href="css/fonts.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body style="background-color: #082d3e;" class="noselect">

    <nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container">
        <div class="row">
          <div class="col-xs-2">
            <a class="navbar-back" href="index.html"><br>
              < Home
            </a>
          </div>
          <div class="col-xs-8">
            <p class="navbar-title text-center">Transportation Use Case</p>
          </div>
          <div class="col-xs-2">
            <a class="navbar-brand navbar-right" href="#">
              <img alt="Intel" src="images/Intel_Logo_White.png">
            </a>
          </div>
        </div>
      </div>
    </nav>

    <div class="container container-video">
      <video poster="images/transportation_background.jpg" id="bgvid" width="1366px">
        <source src="videos/Truck_Intro.mp4" type="video/mp4">
      </video>
    </div>

    <div class="container container-transportation hidden">
      <div class="row" style="margin-top: 100px;">
      </div>

      <div class="row">
        <div class="col-md-offset-6 col-xs-2">
          <button id="reset_btn" type="button" class="btn btn-truck"><img src="images/reset_btn.png" alt="Reset"></button>
        </div>
        <div class="col-xs-2">
          <button id="viewLog" type="button" class="btn btn-truck" data-toggle="modal" data-target="#logModal"><img src="images/log_btn.png" alt="View Log"></button>
        </div>
        <div class="col-xs-2">
        <button type="button" class="btn btn-truck" data-toggle="modal" data-target="#helpModal"><img src="images/howto_btn.png" alt="Help"></button>
        </div>
      </div>

      <div class="row" style="margin-top: 25px;">
      </div>

      <div class="row noselect" style="height: 400px;">
        <div class="col-md-offset-6 col-xs-6">
          <div class="row">
            <div class="sensor tempsensor" id="t1sensor">
            <div class="tempheader">TEMPERATURE (<span class="fartemp selected">&#176;F</span> / <span class="celtemp">&#176;C</span>)</div>
                <div class="increasethreshold"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span></div>
                <div class="decreasethreshold"><span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span></div>
                <div id="main">
                    <div class="thresholdArc" id="t1_temp_threshold" class="selectedRadial noselect"></div>
                    <div class="currentArc" id="t1_temp_current" class="selectedRadial noselect"></div>
                </div>
            </div>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-md-offset-8 col-xs-4"><h4 class="text-uppercase usecase_steps text-right">Use Case Steps</h4></div>
      </div>

      <div class="row">
        <div class="col-xs-4"></div>
        <div class="col-xs-2 hidden" id="step1i">
          <img alt="step 1" src="images/step1_inactive.png" style="width: 200px;">
        </div>
        <div class="col-xs-2 show" id="step1a">
          <img alt="step 1" src="images/step1_active.png" style="width: 200px;">
        </div>
        <div class="col-xs-2 show" id="step2i">
          <img alt="step 2" src="images/step2_inactive.png" style="width: 200px;">
        </div>
        <div class="col-xs-2 hidden" id="step2a">
          <img alt="step 2" src="images/step2_active.png" style="width: 200px;">
        </div>
        <div class="col-xs-2 show" id="step3i">
          <img alt="step 3" src="images/step3_inactive.png" style="width: 200px;">
        </div>
        <div class="col-xs-2 hidden" id="step3a">
          <img alt="step 3" src="images/step3_active.png" style="width: 200px;">
        </div>
        <div class="col-xs-2 show" id="step4i">
          <img alt="step 4" src="images/step4_inactive.png" style="width: 200px;">
        </div>
        <div class="col-xs-2 hidden" id="step4a">
          <img alt="step 4" src="images/step4_active.png" style="width: 200px;">
        </div>
      </div>

    </div> <!-- /container -->

      <!-- Modal -->
    <div class="modal fade" id="helpModal" role="dialog">
      <div class="modal-dialog modal-lg modal-truck">

        <!-- Modal content-->
        <div class="modal-content" style="background-color: rgb(236, 236, 236);">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Setup Instructions</h4>
          </div>
          <div class="modal-body">
            <div class="completed-step hidden">
              <p>Completed setup view:</p>
              <img class='center-block' src='images/help_everything.jpg'>
            </div>
            <div class="all-parts show">
              <p>The following parts are required for this use case. Mouse over each part to get more information or see what the finished setup looks like. </p>
              <p>Close to go to the use case.</p>
              <table class="table table-condensed" style="margin-left: -10px;">
                <tr>
                  <td>
                    <table>
                      <tr>
                        <td class="parts-hover" id="item_sdcard" data-toggle="popover" data-trigger="hover focus" title="8 GB Micro-SD Card" data-container="body" data-content="<p>A Micro SD Memory card.</p><img class='img-responsive' src='images/popup_sdcard.jpg'><p><strong>Instructions:</strong></p><p>Goes into <strong>left silver insert</strong> of Intel Galileo Gen 2 board.</p>" data-placement="right" data-html="true"><img src="images/item_sdcard.png"></td>
                        <td class="parts-hover" id="item_button" data-toggle="popover" data-trigger="hover focus" title="Grove Button" data-container="body" data-content="<p>One independent button, configured with pull-down resistor.</p><img class='img-responsive' src='images/popup_button.jpg'><br/><p><strong>Instructions:</strong></p><p>Plugs in to <strong>D2</strong> connector of Arduino Sheild.</p>" data-placement="right" data-html="true"><img src="images/item_button.png"></td>
                      </tr>
                      <tr>
                        <td class="parts-hover" id="item_led" data-toggle="popover" data-trigger="hover focus" title="LED Light" data-container="body" data-content="<p>A red LED light.</p><img class='img-responsive' src='images/popup_led.jpg'><br/><p><strong>Instructions:</strong></p><p><strong>Longer end of LED light goes into (+)</strong> and then plugs in to <strong>D4</strong> of Arduino Shield</p>" data-placement="right" data-html="true"><img src="images/item_led.png"></td>
                        <td class="parts-hover" id="item_temperature" data-toggle="popover" data-trigger="hover focus" title="Temperature Sensor" data-container="body" data-content="<p>Uses a thermistor which returns the ambient temperature in the form of a resistance value.</p><img class='img-responsive' src='images/popup_temperature.jpg'><br/><p><strong>Instructions:</strong></p><p>Plugs in to to A0 of Arduino Shield.</p>" data-placement="right" data-html="true"><img src="images/item_temperature.png"></td>
                      </tr>
                      <tr>
                        <td class="parts-hover" id="item_buzzer" data-toggle="popover" data-trigger="hover focus" title="Buzzer" data-container="body" data-content="<p>Will emit a tone when the output is high.</p><img class='img-responsive' src='images/popup_buzzer.jpg'><br/><p><strong>Instructions:</strong></p><p>Plugs in to to D5 of Arduino Shield.</p>" data-placement="top" data-html="true"><img src="images/item_buzzer.png"></td>
                        <td class="parts-hover" id="item_touch" data-toggle="popover" data-trigger="hover focus" title="Touch Sensor" data-container="body" data-content="<p>It can detect the change in capacitance when a finger is near it.</p><img class='img-responsive' src='images/popup_touch.jpg'><br/><p><strong>Instructions:</strong></p><p>Plugs in to to <strong>D3</strong> of Arduino Shield.</p>" data-placement="top" data-html="true"><img src="images/item_touch.png"></td>
                      </tr>
                    </table>
                  </td>
                  <td class="parts-hover" id="item_galileo" data-toggle="popover" data-trigger="hover focus" title="Intel Galileo Gen 2" data-container="body" data-content="<p>Intel Galileo Gen 2 development board, the first in a family of Arduino-certified development boards based on Intel architecture and specifically designed for makers, students, educators and DIY electronics enthusiasts.</p>" data-placement="left" data-html="true"><img src="images/item_galileo.png"></td>
                  <td>
                    <table>
                      <tr><td class="parts-hover" id="item_arduino" data-toggle="popover" data-trigger="hover focus" title="Arduino Shield" data-container="body" data-content="<p>As an expansion board, Base Shield v2 has many Grove connectors, making it convenient for you to use Grove products together. And It is compatible with a series of Arduino products.</p><img class='img-responsive' src='images/popup_arduino.jpg'><br/><p><strong>Instructions:</strong></p><p>Plug the Arduino Shield into the <strong>Galileo Gen 2 pinouts</strong>.</p>" data-placement="left" data-html="true"><img src="images/item_arduino.png"></td></tr>
                      <tr><td class="parts-hover" id="item_lcd" data-toggle="popover" data-trigger="hover focus" title="LCD RGB Backlight" data-container="body" data-content="<p>This display enables you to set the color to whatever you like. Also supports user-defined characters.</p><img class='img-responsive' src='images/popup_lcd.jpg'><br/><p><strong>Instructions:</strong></p><p>Plug into <strong>I2C</strong> in Arduino Shield.</p>" data-placement="left" data-html="true"><img src="images/item_lcd.png"></td></tr>
                    </table>
                  </td>
                </tr>
              </table>
            </div>
          </div>
          <div class="modal-footer">
            <!-- <button type="button" class="btn btn-default hidden" id="help_prev">Previous</button> -->
            <button type="button" class="btn btn-default" id="help_next" data-target="#completedModal">View Finished Setup</button>
          </div>
        </div>
      </div>
    </div>

      <!-- Modal -->
    <div class="modal fade" id="logModal" role="dialog">
      <div class="modal-dialog modal-lg modal-truck">

        <!-- Modal content-->
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">View Log</h4>
          </div>
          <div class="modal-body">
            <div id="canvas-holder1">
                <canvas id="chart1" height="250" width="300" style="width: 300px; height: 250px;"></canvas>
            </div>
            <div id="chartjs-tooltip"></div>
            <table id="activity_log" class="table table-striped table-hover">
              <tr>
                  <th>ALERT #</th>
                  <th>TIME</th>
                  <th>THRESHOLD (F)</th>
                  <th>TEMPERATURE (F)</th>
                  <th>STATUS</th>
              </tr>
               <tr class="data_row">
                  <td>1</td>
                  <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                  <td class="table_temp_threshold">70</td>
                  <td class="table_temperature">65</td>
                  <td class="table_status">Button Pressed</td>
              </tr>
               <tr class="data_row">
                  <td>2</td>
                  <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                  <td class="table_temp_threshold">70</td>
                  <td class="table_temperature">69</td>
                  <td class="table_status">Temperature Rising</td>
              </tr>
               <tr class="data_row">
                  <td>3</td>
                  <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                  <td class="table_temp_threshold">70</td>
                  <td class="table_temperature">72</td>
                  <td class="table_status">Exceeded Threshold</td>
              </tr>
               <tr class="data_row">
                  <td>4</td>
                  <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                  <td class="table_temp_threshold">70</td>
                  <td class="table_temperature">73</td>
                  <td class="table_status">Buzzer Stopped</td>
              </tr>
               <tr class="data_row">
                  <td>5</td>
                  <td class="table_time">01-Jan-2015 11:47:28 PM</td>
                  <td class="table_temp_threshold">68</td>
                  <td class="table_temperature">70.8</td>
                  <td class="table_status">Door Closed</td>
              </tr>
            </table>

          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          </div>
        </div>

      </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/d3.min.js"></script>
    <script type="text/javascript" src="js/Chart.min.js"></script>
    <script type="text/javascript" src="js/radialProgress.js"></script>
    <script type="text/javascript" src="js/moment.min.js"></script>
    <script type="text/javascript" src="js/demo-core.js"></script>
    <script type='text/javascript'>
        $(document).ready(function() {
            DEMO_CORE.routes = {
                currentReadingsUrl: "/ExpKit/getData?value=current",
                logEntriesUrl: "/ExpKit/getData?value=log",
                tempThresholdUrl: "/ExpKit/threshold",
                demoStatusUrl: "/ExpKit/demo",
            };
            var INITIAL_STEP_VALUE = 0;
            var INITIAL_DOOR_STATUS = false; // closed
            var MAX_POINTS_IN_GRAPH = 15;
            var VIDEO_DEMO_READY_TIMESTAMP = 9.5;
            var VIDEO_DOORS_FULLY_OPEN_RED_TIMESTAMP = 15;
            var VIDEO_DOORS_FULLY_OPEN_GREEN_TIMESTAMP = 17; // 13.5;
            var VIDEO_DOORS_FULLY_CLOSED_TIMESTAMP = 19.750;

            var currentStep = INITIAL_STEP_VALUE;
            var currentDoorStatus = INITIAL_DOOR_STATUS;

            $(function () {
                $('[data-toggle="popover"]').popover();
            })

            var truckbg_vid = document.getElementById("bgvid");

            if (document.location.hash === '#skip_video') {
              truckbg_vid.currentTime = VIDEO_DEMO_READY_TIMESTAMP;
            }

            truckbg_vid.play();

            // Check to see if the video has gotten to our designated pause
            // point every 100ms.
            var pauseVideoInterval = setInterval(function() {
              if (truckbg_vid.currentTime >= VIDEO_DEMO_READY_TIMESTAMP) {
                truckbg_vid.pause();

                $('.container-transportation').removeClass("hidden");
                /*$('#helpModal').modal('show');*/

                // drawChart();
                refreshTemp();

                // Start polling the feed and log APIs
                DEMO_CORE.updateCurrentSensorReadings();
                pollLog();

                clearInterval(pauseVideoInterval);
              }
            }, 100);

            var STEP_PROGRESS = {
                // These functions update the UI for the completion of each step
                step1: function() {
                    $('#step1i').removeClass('hidden').addClass('show');
                    $('#step1a').removeClass('show').addClass('hidden');

                    //do step 2
                    $('#step2i').removeClass('show').addClass('hidden');
                    $('#step2a').removeClass('hidden').addClass('show');
                },

                step2: function() {
                    $('#step2i').removeClass('hidden').addClass('show');
                    $('#step2a').removeClass('show').addClass('hidden');

                    //do step 3
                    $('#step3i').removeClass('show').addClass('hidden');
                    $('#step3a').removeClass('hidden').addClass('show');
                },

                step3: function() {
                    $('#step3i').removeClass('hidden').addClass('show');
                    $('#step3a').removeClass('show').addClass('hidden');

                    //do step 4
                    $('#step4i').removeClass('show').addClass('hidden');
                    $('#step4a').removeClass('hidden').addClass('show');
                },

                step4: function() {
                    $('#step4i').removeClass('hidden').addClass('show');
                    $('#step4a').removeClass('show').addClass('hidden');
                },
            };

            function updateStep(newStep) {
                if (newStep > currentStep) {
                    var stepName = 'step' + newStep;
                    STEP_PROGRESS[stepName]();
                    currentStep = newStep;
                }
            }

            function updateDoor(newStatus) {
                if (newStatus !== currentDoorStatus) {
                    if (newStatus) {
                        openTruckDoor();
                    } else {
                        closeTruckDoor();
                    }
                    currentDoorStatus = newStatus;
                }
            }

            function openTruckDoor() {
                truckbg_vid.pause();
                truckbg_vid.currentTime = VIDEO_DEMO_READY_TIMESTAMP;
                truckbg_vid.play();

                setTimeout(function() {
                    truckbg_vid.pause();
                    truckbg_vid.currentTime = VIDEO_DOORS_FULLY_OPEN_RED_TIMESTAMP;
                  },
                  1000 * (VIDEO_DOORS_FULLY_OPEN_RED_TIMESTAMP - VIDEO_DEMO_READY_TIMESTAMP)
                );
            };

            function closeTruckDoor() {
              truckbg_vid.pause();
              truckbg_vid.currentTime = VIDEO_DOORS_FULLY_OPEN_GREEN_TIMESTAMP;
              truckbg_vid.play();

              setTimeout(function() {
                  truckbg_vid.pause();
                  truckbg_vid.currentTime = VIDEO_DOORS_FULLY_CLOSED_TIMESTAMP;
                },
                1000 * (VIDEO_DOORS_FULLY_CLOSED_TIMESTAMP - VIDEO_DOORS_FULLY_OPEN_GREEN_TIMESTAMP)
              );
            };

            // CHART

            var lineChartData = {
                labels : [],
                datasets : [
                  {
                    label: "Temperature",
                    fillColor : "rgba(255,204,103,0.2)",
                    strokeColor : "rgba(255,204,103,0.6)",
                    pointColor : "rgba(255,204,103,0.8)",
                    pointStrokeColor : "rgba(255,204,103,1.0)",
                    pointHighlightFill : "#fff",
                    pointHighlightStroke : "rgba(220,220,220,1)",
                    data : []
                  }
                ]
            };

            function drawChart() {
              var chart = document.getElementById("chart1");
              if (!window.myLine) {
                  var ctxfull = chart.getContext("2d");
                  window.myLine = new Chart(ctxfull).Line(lineChartData, {
                    responsive: false
                  });
              }
            }

            // Stash the chart size before actually attempting to draw the chart
            // because drawing the chart in a hidden div messes with the chart
            // size.
            var chart1Size = null;
            setTimeout(function() {
              var jChart = $(document.getElementById("chart1"));
              if (!chart1Size) {
                  chart1Size = {
                      width: jChart.attr('width'),
                      height: jChart.attr('height')
                  };
              }
            }, 50);

            $('#viewLog').on('click', function() {
                setTimeout(function() {
                    // fix height/width, which seem to get mangled when the
                    // graph is drawn in an invisible modal....
                    var jChart = $(document.getElementById("chart1"));
                    jChart.css({
                        height: chart1Size.height + 'px',
                        width: chart1Size.width + 'px'
                    });
                    jChart.attr('height', chart1Size.height);
                    jChart.attr('width', chart1Size.width);
                    drawChart();
                }, 300);
            });

            // TEMPERATURE ARC

            var t1Degree="F";

            t1_thresholdTemp = 0;
            t1_currentTemp = 0;

            var t1_temp_threshold=d3.select(document.getElementById('t1_temp_threshold'));
            var t1_temp_current=d3.select(document.getElementById('t1_temp_current'));

            function refreshTemp(){
                if(t1Degree=="F"){
                    setArcs('t1_temp_threshold','t1_temp_current', t1_thresholdTemp, t1_currentTemp, "temp");
                } else {
                    setArcs('t1_temp_threshold','t1_temp_current', (t1_thresholdTemp-32)*5/9, (t1_currentTemp-32)*5/9, "temp");
                }
            }

            function setArcs(thresholdDiv, currentDiv, thresholdValue, currentValue, arcType) {
                if(currentValue<0) { currentValue=0; }
                if(thresholdValue<0) { thresholdValue=0; }

                thresholdDiv = $('#' + thresholdDiv);
                var rp1 = radialProgress(thresholdDiv[0])
                        .diameter(140)
                        .minValue(0)
                        .maxValue(thresholdDiv.data('maxValue') || 100)
                        .value(thresholdValue)
                        .render();

                currentDiv = $('#' + currentDiv);
                var rp2 = radialProgress(currentDiv[0])
                        .diameter(130)
                        .minValue(0)
                        .maxValue(currentDiv.data('maxValue') || 100)
                        .threshold(thresholdValue)
                        .arctype(arcType)
                        .value(currentValue)
                        .render();
            }

            $('.tempheader').on('click', function() {
                var truckid= ($(this).parent().attr("id"));
                $('#'+truckid+' .fartemp').toggleClass('selected');
                $('#'+truckid+' .celtemp').toggleClass('selected');

                if(truckid=="t1sensor") {
                    if($('#'+truckid+' .fartemp').hasClass('selected')) {
                        t1Degree="F";
                        DEMO_CORE.settings.temperature_units = "Fahrenheit";
                    } else {
                        t1Degree="C";
                        DEMO_CORE.settings.temperature_units = "Celsius";
                    }
                }

                refreshTemp();
            });

            $('.increasethreshold').on('click', function() {
                var parent = $(this).parent();
                var buttonid = parent.attr("id");
                if(buttonid=="t1sensor") {
                    changeThreshold(parent, t1_thresholdTemp + 1);
                }
            });

            $('.decreasethreshold').on('click', function() {
                var parent = $(this).parent();
                var buttonid = parent.attr("id");
                if(buttonid=="t1sensor") {
                    changeThreshold(parent, t1_thresholdTemp - 1);
                }
            });

            function changeThreshold(whichThreshold, newValue) {
                if(newValue<0) {newValue=0;}
                var updateValue = newValue;
                var url = DEMO_CORE.buildServerUrl(
                    DEMO_CORE.routes.tempThresholdUrl);
                url += "?value=" + encodeURIComponent(newValue.toString());
                $.ajax(url,
                        {
                            dataType: 'json',
                            type: DEMO_CORE.defaultHttpMethod,
                            cache: DEMO_CORE.allowCaching,
                        }
                    ).
                    done(function(data, textStatus, jqXhr) {
                        updateValue = parseInt(data[0].threshold, 10);
                    }).
                    always(function() {
                        switch (whichThreshold.attr('id')) {
                            case "t1sensor":
                                t1_thresholdTemp = updateValue;
                                refreshTemp();
                                break;
                        }
                    });
            }

            // Help Modal

            $('#help_next').on('click', function () {
                $('.completed-step').toggleClass('hidden');
                $('.completed-step').toggleClass('show');

                $('.all-parts').toggleClass('show');
                $('.all-parts').toggleClass('hidden');

                if($(this).text()=='View All Parts') {
                  $(this).text('View Finished Setup');
                } else {
                  $(this).text('View All Parts');
                }
            })


            // RESET FUNCTION

            $('#reset_btn').on('click', function() {
              resetDemoStatus();
              resetUseCase();
            })

            function resetUseCase() {
              truckbg_vid.pause();
              truckbg_vid.currentTime = 9.5;

              $('#step1i').addClass('hidden');
              $('#step1i').removeClass('show');
              $('#step1a').addClass('show');
              $('#step1a').removeClass('hidden');

              $('#step2i').addClass('show');
              $('#step2i').removeClass('hidden');
              $('#step2a').addClass('hidden');
              $('#step2a').removeClass('show');

              $('#step3i').addClass('show');
              $('#step3i').removeClass('hidden');
              $('#step3a').addClass('hidden');
              $('#step3a').removeClass('show');

              $('#step4i').addClass('show');
              $('#step4i').removeClass('hidden');
              $('#step4a').addClass('hidden');
              $('#step4a').removeClass('show');

              t1Degree="F";

              t1_thresholdTemp = 0;
              t1_currentTemp = 0;

              refreshTemp();
            }

            function initializeDemoStatus() {
                resetDemoStatus();
                DEMO_CORE.shouldPollSensors = true;
            }

            function resetDemoStatus() {
                $.ajax(DEMO_CORE.buildServerUrl('/ExpKit/demo?value=reset'), {
                        dataType: 'text',
                        type: DEMO_CORE.defaultHttpMethod,
                        cache: DEMO_CORE.allowCaching,
                    }).
                    done(function(data, textStatus, jqXhr) {
                        console.log("Demo Reset Status: " + data);

                        currentStep = INITIAL_STEP_VALUE;
                        updateStep(currentStep);

                        currentDoorStatus = INITIAL_DOOR_STATUS;
                        updateDoor(currentDoorStatus);
                    }).
                    fail(function(jqXhr, textStatus, errorThrown) {
                        console.log("initializeDemoStatus error " + textStatus + ": ", errorThrown);
                    });
            }

            function updateTempGraphData(newData, maxSize) {
                var points;
                var value = DEMO_CORE.fahrenheitTempToPreferredUnit(newData.temperature);
                var label = '';
                    // newData.timestamp.format(DEMO_CORE.getHourFormat(true));
                if (window.myLine) {
                    points = window.myLine.datasets[0].points;
                    if (points.length >= maxSize) {
                      window.myLine.removeData();
                    }
                    window.myLine.addData([value], label);
                    window.myLine.update();
                } else {
                    points = lineChartData.datasets[0].data;
                    lineChartData.labels.splice(0,
                        lineChartData.labels.length - (maxSize - 1));
                    points.splice(0,
                        points.length - (maxSize - 1));
                    points.push(value);
                    lineChartData.labels.push(label);
                }
            }

            function formatFeedData(data) {
                return {
                    timestamp: DEMO_CORE.parseTimestamp(
                        DEMO_CORE.fixupTimestamp(data.timestamp)),
                    temperature: parseFloat(data.temp),
                    threshold: parseInt(data.threshold, 10),
                    door_status: DEMO_CORE.isTruthy(data.door_status),
                    demo_status: DEMO_CORE.isTruthy(data.demo_status),
                    demo_step: parseInt(data.current_step, 10),
                };
            }

            function formatLogData(entry) {
                return {
                    timestamp: DEMO_CORE.parseTimestamp(
                                DEMO_CORE.fixupTimestamp(entry.timestamp)),
                    temperature: parseFloat(entry.temp),
                    threshold: parseInt(entry.threshold, 10),
                    status: entry.event
                };
            };

            function formatLogEntries(logEntries) {
                return $.map(logEntries, formatLogData);
            }

            function updateLogTable(logTable, logEntries) {
                var rows = logTable.find('tr.data_row');
                if (logEntries.length > rows.length) {
                  rows.last().parent().append(rows.last().clone());
                  rows = logTable.find('tr.data_row');
                }
                rows.each(function(index, row) {
                    var entry = logEntries[index];
                    var cells = $(row).find('td');
                    if (entry) {
                        cells.first().parent().css('display', 'table-row');
                        cells.first().html(index + 1);
                        cells.filter('.table_time').html(
                                DEMO_CORE.formatDateTime(entry.timestamp));
                        var displayThreshold = DEMO_CORE.fahrenheitTempToPreferredUnit(entry.threshold, 1);
                        var displayTemp = DEMO_CORE.fahrenheitTempToPreferredUnit(entry.temperature, 1);
                        cells.filter('.table_temp_threshold').html(displayThreshold);
                        cells.filter('.table_temperature').html(displayTemp);
                        cells.filter('.table_status').html(entry.status);

                        if (entry.temperature >= entry.threshold) {
                          $(row).addClass('alarm');
                        } else {
                          $(row).removeClass('alarm');
                        }
                    } else {
                        cells.first().parent().css('display', 'none');
                    }
                });
            }

            function pollLog() {
                if (DEMO_CORE.shouldPollSensors) {
                    $.ajax(DEMO_CORE.buildServerUrl(DEMO_CORE.routes.logEntriesUrl), {
                            dataType: 'json',
                            type: DEMO_CORE.defaultHttpMethod,
                            cache: DEMO_CORE.allowCaching,
                        }).
                        done(function(data, textStatus, jqXhr) {
                            var logEntries = formatLogEntries(data);
                            updateLogTable($('#activity_log'), logEntries);
                        }).
                        fail(function(jqXhr, textStatus, errorThrown) {
                            console.log("error " + textStatus + ": ", errorThrown);
                        }).
                        always(function() {
                          // Schedule poll only after AJAX call finishes
                          DEMO_CORE.scheduleNextPoll(pollLog);
                        });
                } else {
                  // Set timer for next check
                  DEMO_CORE.scheduleNextPoll(pollLog);
                }
            };

            $(document).on('DEMO_CORE.sensors.current', function(event, data) {
                data = formatFeedData(data[0]);

                // console.log("Current Sensor Readings: ", data);

                t1_currentTemp = data.temperature;
                t1_thresholdTemp = data.threshold;

                refreshTemp();
                updateStep(data.demo_step - 1);
                updateDoor(data.door_status);

                updateTempGraphData(data, MAX_POINTS_IN_GRAPH);
            });

            initializeDemoStatus();
        });
    </script>
  </body>
</html>
